<?php

// +----------------------------------------------------------------------
// | Author: pp <124910168@qq.com>
// +----------------------------------------------------------------------

namespace app\client\controller;

use controller\BasicClient;
use service\DataService;
use service\ToolsService;
use service\LogService;
use think\Db;

/**
 * 传承人信息管理
 * Class Companyclass
 * @package app\client\controller
 */
class Company extends BasicClient
{

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        // $this->user = session('c_user');
        // $this->uid = $this->user['create_by'];
        // halt($this->uid);
        // halt(model('Area')->getOpenAreaList());
    }

    /**
     * 指定当前数据表
     * @var string
     */
    protected $categoryTable = 'Client';

    /*
     * 传承人信息管理
     */
    public function index()
    {
        $this->title='传承人信息管理';
        //传承人分类
        // $store_class=model('store_class')->getStoreClassList(array(),1,30);
    	// $this->assign('store_class',$store_class);
        return $this->_form('client','', 'id', ['id' => $this->uid]);
    }
    public function _index_form_filter(&$data) {
        if ($this->request->isPost()) {
            // halt($data);


            if(!empty($data['work_start'])){
                $data['work_start']=strtotime($data['work_start']);
            }

            if(!empty($data['id_images'])){
                $data['id_images']=trim(implode(';',$data['id_images']),',');
            }

            if(!empty($data['cert_images'])){
                $data['cert_images']=trim(implode(';',$data['cert_images']),',');
            }

            if (isset($data['authorize']) && is_array($data['authorize'])) {
                $data['authorize'] = join(',', $data['authorize']);
            }
            
            //商家分类  用,分隔
            if(!empty($data['sc_id'])){
            	$data['sc_id']=trim(implode(',',$data['sc_id']),',');
            }
            if(!empty($data['type'])){
                $data['type']=trim(implode(',',$data['type']),',');
            }
            if(!empty($data['readgroup'])){
                $data['readgroup']=trim(implode(',',$data['readgroup']),',');
            }
            
            if (isset($data['id'])) {
                unset($data['username']);
            } elseif (Db::name($this->table)->where('username', $data['username'])->find()) {
                $this->error('用户账号已经存在，请使用其它账号！');
            }
        } else {

            if(!empty($data['work_start'])){
                $data['work_start']=date('Y-m-d',$data['work_start']);
            }
            if(!empty($data['id_images'])){
                $data['id_images']=explode(';',$data['id_images']);
            }
            if(!empty($data['cert_images'])){
                $data['cert_images']=explode(';',$data['cert_images']);
            }
            if(!empty($data['readgroup'])){
                $data['readgroup']=explode(',',$data['readgroup']);
            }else{
                $data['readgroup'] = [1];
            }
            if(!empty($data['aid'])){
                $data['aid']=explode(',',$data['aid']);
            }
            if(!empty($data['nid'])){
                $data['nid']=explode(',',$data['nid']);
            }
            if(!empty($data['did'])){
                $data['did']=explode(',',$data['did']);
            }

            // //获取地区
            // $areaList = $this->_getAreaTrees('Area', ['area_open' => 1, 'area_id' => ['in', $this->aids]]);
            // $this->assign('areaList', $areaList);
            $data['authorize'] = explode(',', isset($data['authorize']) ? $data['authorize'] : '');
            $this->assign('authorizes', Db::name('ClientAuth')->where('create_by',0)->select());

            $newareas = ToolsService::arr2subs($this->newareas, $data['aid']);
            $this->assign('newareas', $newareas);
            $newnations = ToolsService::arr2subss($this->newnations, $data['nid']);
            $this->assign('newnations', $newnations);
            $newdiseases = ToolsService::arr2subss($this->newdiseases, $data['did']);
            $this->assign('newdiseases', $newdiseases);
        }
    }

    /**
     * ajax获取地区经纬度
     */
    public function ajax(){
        $post = input('post.');

        $newdata = urlencode($post['address']);

        $url = "http://api.map.baidu.com/geocoder/v2/?address=".$newdata."&output=json&ak=7b92b3afff29988b6d4dbf9a00698ed8";

        $address_data = file_get_contents($url);
        $json_data = json_decode($address_data);
        $lng = $json_data->result->location->lng;
        $lat = $json_data->result->location->lat;
        $data['lng'] = strval($lng);
        $data['lat'] = strval($lat);
        $data['status'] = 1;
//            $this->ajaxReturn($data);
        return $data;


    }
    
    /**
     * 表单数据默认处理
     * @param array $data
     */
    public function _form_filter(&$data) {
        if ($this->request->isPost()) {
            //商家分类  用,分隔
            if(!empty($data['sc_id'])){
            	$data['sc_id']=trim(implode(',',$data['sc_id']),',');
            }
            
        }
    }

    /**
     * 相册照片列表
     */
    public function picture()
    {
        $list = Db::name('CompanyPhotoPic')->where('photo_id',$this->request->get('id'))->select();
        $html = '';
        foreach ($list as $key => $value){
            $html .= '<div id="img_'.$value['id'].'">';
            $html .= '<img data-tips-image src="'.$value['photo_picture_url'].'"/>';
            $html .= '<br><a href="JavaScript:void(0)" onclick="del_img('.$value['id'].')">删除</a>';
            $html .= ' </div>';
        }
        return $this->fetch('',['id'=>$this->request->get('id'),'html'=>$html]);
    }

    /**
     * 相册照片添加
     */
    public function add_photo()
    {
        $html = '';
        foreach (explode("|",input('value')) as $key => $value){
            if ($result = Db::name('CompanyPhotoPic')->insert(['photo_id'=>input('id'),'photo_picture_url'=>$value],$replace = false, $getLastInsID = true)) {
                $html .= '<div id="img_'.$result.'">';
                $html .= '<img data-tips-image src="'.$value.'"/>';
                $html .= '<br><a href="JavaScript:void(0)" onclick="del_img('.$result.')">删除</a>';
                $html .= ' </div>';
            }
        }
        if ($html){
            die($html);
        } else {
            die('0');
        }
    }

    /**
     * 相册照片删除
     */
    public function DelPicture()
    {
        $table = "CompanyPhotoPic";
        if (DataService::update($table)) {
            die('删除成功！');
        }
        die("删除失败，请稍候再试！");
    }
    
    /**
     * 新增/编辑所在区域
     */
    public function edit_area() {
    	$model_store=model('store');
        $post=$this->request->post();
        $get=$this->request->param();
        if ($this->request->isPost()) {
            $data = array(
                'area_id' => $post['area_id'],
                'city_id' => $post['city_id'],
                'area_info' => $post['region'],
            );
            $id = intval($post['id']);
            $condition = array();
            $condition['id'] = $id;
            $update = $model_store->uptArea($data,$condition);
            if (!$update){
            	$this->error('操作失败',"/client#".url('client/company/index')."?spm=".get_spm_by_classuri2('client/company/index',"client_menu"));
            }
            LogService::write('系统管理', '传承人信息修改成功');
            $this->success('操作成功',"/client#".url('client/company/index')."?spm=".get_spm_by_classuri2('client/company/index',"client_menu"));
        } elseif (is_numeric($get['id']) > 0) {
            //编辑
            $id = intval($get['id']);
            $store_info=$model_store->getStoreInfoByID($id);
//          halt($store_info);
            
            if (empty($store_info) && !is_array($store_info)){
            	$this->error('参数不正确','');
            }
            $this->assign('address_info',$store_info);
        }
        return $this->fetch('edit_area');
    }
}
